package com.sanjiayi.controller;

import com.sanjiayi.pojo.ChatMessage;
import com.sanjiayi.result.Result;
import com.sanjiayi.service.ChatService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/chat")
@Api(tags = "聊天相关接口")
public class ChatController {

    @Autowired
    private ChatService chatService;

    @GetMapping("/11history")
    @ApiOperation("获取聊天历史记录")
    public Result<List<ChatMessage>> getChatHistory(
            @ApiParam("用户1 ID") @RequestParam Integer userId1,
            @ApiParam("用户2 ID") @RequestParam Integer userId2,
            @ApiParam("限制条数") @RequestParam(required = false) Integer limit) {
        try {
            List<ChatMessage> messages = chatService.getChatHistory(userId1, userId2, limit);
            return Result.ok(messages);
        } catch (Exception e) {
            return Result.error("获取聊天记录失败");
        }
    }

    @GetMapping("/unread/count")
    @ApiOperation("获取未读消息数")
    public Result<Integer> getUnreadCount(@ApiParam("用户ID") @RequestParam Integer userId) {
        try {
            int count = chatService.getUnreadCount(userId);
            return Result.ok(count);
        } catch (Exception e) {
            return Result.error("获取未读消息数失败");
        }
    }

    @PostMapping("/read")
    @ApiOperation("标记消息为已读")
    public Result markAsRead(
            @ApiParam("发送者ID") @RequestParam Integer senderId,
            @ApiParam("接收者ID") @RequestParam Integer receiverId) {
        try {
            chatService.markAsRead(senderId, receiverId);
            return Result.ok();
        } catch (Exception e) {
            return Result.error("标记已读失败");
        }
    }

    @GetMapping("/recent")
    @ApiOperation("获取最近聊天列表")
    public Result<List<ChatMessage>> getRecentChats(@ApiParam("用户ID") @RequestParam Integer userId) {
        try {
            List<ChatMessage> recentChats = chatService.getRecentChats(userId);
            return Result.ok(recentChats);
        } catch (Exception e) {
            return Result.error("获取最近聊天列表失败");
        }
    }

    @GetMapping("/messages")
    @ApiOperation("获取与指定用户的最新消息")
    public Result<List<ChatMessage>> getMessages(
            @ApiParam("当前用户ID") @RequestParam Integer userId,
            @ApiParam("对方用户ID") @RequestParam Integer otherUserId,
            @ApiParam("消息数量限制") @RequestParam(required = false, defaultValue = "20") Integer limit) {
        try {
            List<ChatMessage> messages = chatService.getChatHistory(userId, otherUserId, limit);
            return Result.ok(messages);
        } catch (Exception e) {
            return Result.error("获取消息失败");
        }
    }
}